from django.shortcuts import render
from django.views import View
from django.core.paginator import Paginator
from goods.models import GoodsCategory, SKU
from meiduo1.utils.my_category import get_categories
from django import http

class SkuListView(View):
    def get(self,request,category_id,page_num):

        #1,获取分类信息,获取参数
        categories = get_categories()
        sort = request.GET.get('sort','default')
        if sort == 'price':
            sort_fild = '-price'
            sort = 'price'
        elif sort == 'hot':
            sort_fild = '-hot'
            sort = 'hot'
        else:
            sort_fild = '-create_time'
            sort = 'default'


        #2,获取分类对象
        category = GoodsCategory.objects.get(id=category_id)
        #分页查询
        skus = SKU.objects.filter(category_id=category_id).order_by(sort_fild)
        paginator = Paginator(object_list=skus,per_page=5)#创建分类对像
        page = paginator.page(page_num)#获取page_num页
        skus_list = page.object_list#获取page_num所有对象
        current_page = page.number#当前页
        total_page = paginator.num_pages
        #拼接数据,返回响应
        context = {
            "categories":categories,
            "category":category,
            "skus_list":skus_list,
            "current_page":current_page,
            "total_page":total_page,
            "sort":sort
         }

        return render(request,'list.html',context=context)

class HotSkuView(View):#人气获取
    def get(self,request,category_id):
        skus = SKU.objects.filter(category_id=category_id).order_by('-sales')[:3]

        #拼接数据
        hot_sku_list = []
        for sku in skus:
            sku_dict = {
                "id":sku.id,
                "default_image_url":sku.default_image_url.url,
                "name":sku.name,
                "price":sku.price
            }
            hot_sku_list.append(sku_dict)
        #返回响应
        return http.JsonResponse({"hot_sku_list":hot_sku_list})
